<script setup lang="ts">
import { useLoadMore } from 'vue-request'
import dialogIcon from '@/static/images/phone_colorful.png'
import { fetchAppointmentListAPI } from '@/apis/fetchAppointmentList'
import { useUserInfoStore } from '@/store/userInfo'
import { useGeneralDataStore } from '@/store/generalData'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const generalDataStore = useGeneralDataStore()

/* -------------------------------- Tab START ------------------------------- */
const selectedTabIndex = ref(0)
const tabs = [{ name: '全部记录' }, { name: '未到店' }, { name: '已到店' }, { name: '已取消' }]
/* --------------------------------- Tab END -------------------------------- */

// 分页列表数据
const { dataList, loading, loadingMore, noMore, loadMore, refresh } = useLoadMore<LoadMoreData<Appointment>>(
  fetchData,
  { isNoMore: d => d?.list.length === d?.total },
)

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

onShow(() => refresh())
onReachBottom(() => loadMore())

/**
 * @description 分页服务函数
 */
async function fetchData(d?: LoadMoreData<Appointment>): Promise<LoadMoreData<Appointment>> {
  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  const query = () => {
    if (selectedTabIndex.value !== 0) {
      return {
        page: _page.toString(),
        limit: '10',
        status: selectedTabIndex.value.toString(),
      }
    }
    else {
      return {
        page: _page.toString(),
        limit: '10',
      }
    }
  }

  const res = await fetchAppointmentListAPI(
    query(),
    userInfoStore.userInfo!.token!,
  )

  return {
    list: res.data?.data.data || [],
    page: _page,
    total: res.data?.data.total || 9999,
  }
}

/* ------------------------------- 事件处理 START ------------------------------- */
function handleSelectTab(item: { index: number, name: string }) {
  selectedTabIndex.value = item.index
  refresh()
}

function handleTapRecord(id: string) {
  router.push({
    name: 'recordDetail',
    params: { id },
  })
}

const isShowDialog = ref(false)

function handleTapContactButton() {
  isShowDialog.value = true
}

function handleCall() {
  isShowDialog.value = false
  uni.makePhoneCall({
    phoneNumber: generalDataStore.generalData?.mobile || '',
    fail: () => { uni.showToast({ title: '取消呼叫', icon: 'none' }) },
  })
}

function handleCancelAppointment(id: string) {
  router.push({
    name: 'cancelAppointment',
    params: { id },
  })
}

function handleTapFollowUpRecord(id: string) {
  router.push({
    name: 'followUpRecord',
    params: { id },
  })
}
/* -------------------------------- 事件处理 END -------------------------------- */
</script>

<template>
  <view class="min-h-screen bg-#F8F8F8">
    <view class="sticky top-0 z-10 w-full bg-white">
      <uv-tabs
        :current="selectedTabIndex"
        :list="tabs"
        line-color="#4999F7"
        :active-style="{ color: '#4999F7', fontWeight: '600' }"
        :inactive-style="{ color: '#848484' }"
        :scrollable="false"
        @change="handleSelectTab"
      />
    </view>
    <Spacer height="24" />
    <view v-if="dataList.length > 0" class="px-24rpx">
      <RecordItem
        v-for="item in dataList"
        :key="item.id"
        :project-names="item.visit_project_ids.split(',')"
        :status="item.status.toString()"
        :time="item.visit_time"
        :doctor="item.doctor_name"
        :price="item.free_money"
        :next-appointment-time="item.next_visit_time"
        @tap="handleTapRecord(item.id.toString())"
        @call="handleTapContactButton"
        @cancel="handleCancelAppointment(item.id.toString())"
        @tap-follow-up-record="handleTapFollowUpRecord(item.id.toString())"
      />
      <!-- 加载更多 -->
      <uv-load-more v-if="dataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
    </view>
    <PageDefault v-else>
      暂无就诊记录
    </PageDefault>
    <Spacer height="240" />
  </view>
  <uv-loading-page :loading="loading && !loadingMore" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
  <uv-overlay :show="isShowDialog" @tap="isShowDialog = false">
    <uv-transition mode="zoom-in" :show="isShowDialog">
      <view class="relative h-screen w-screen">
        <Dialog :icon="dialogIcon" title="请拨打售后客服电话" confirm-label="立即拨打" @cancel="isShowDialog = false" @confirm="handleCall">
          <template #content>
            <view class="text-60rpx text-#333333 leading-84rpx">
              {{ generalDataStore.generalData?.mobile }}
            </view>
          </template>
        </Dialog>
      </view>
    </uv-transition>
  </uv-overlay>
</template>

<route lang="yaml">
name: 'record'
style:
  navigationBarTitleText: '就诊记录'
layout: 'custom'
</route>
